<?php

/** Cms_Resource_Sale_Item */
if (!class_exists('Cms_Resource_Sale_Item')) {
    require_once dirname(__FILE__) . '/Sale/Item.php';
}

/**
 * Cms_Resource_Sale
 *
 * @category   Cms
 * @package    Cms_Model_Resource
 */
class Cms_Resource_Sale extends BIS_Model_Resource_Db_Table_Abstract implements Cms_Resource_Sale_Interface
{
    protected $_name    = 'sale';
    protected $_primary  = 'saleId';
    protected $_rowClass = 'Cms_Resource_Sale_Item';

    /**
     * Get Sale by ID
     *
     * @param int $saleId The sale id
     * @return Cms_Resource_Sale_Item|null
     */
    public function getSaleById($saleId)
    {
        $select = $this->select()
                ->from('sale')
                ->where("saleId = ?", $saleId);
        
        return $this->fetchRow($select);
    }

     /**
     * Get list of Sales
     *
     * @param array      $data order, page, limit, search
     * @return Zend_Db_Table_Rowset|Zend_Paginator
     */
    public function getSales($data= array())
    {
        $select = $this->select();

        $select->from(array('s'=>'sale'),
                        array('saleId' => 's.saleId',
                              'customerName' => 's.customerName',
                              'total' => 's.total',
                              'dateSold' => new Zend_Db_Expr('DATE_FORMAT(s.dateSold, "%d-%b-%Y")'),
                              'soldBy' => 'UPPER(s.soldBy)'
                            ));

        if (isset($data['search'])) {
            $search = $data['search'];
            $select->where("s.soldBy like ? OR s.customerName like ?", "%$search%");
        }

        if (isset($data['order'])) {
            $select->order($data['order']);
        }

	if (isset($data['page'])) {
		$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
		$paginator = new Zend_Paginator($adapter);
		$paginator->setItemCountPerPage($data['limit'])
	          	  ->setCurrentPageNumber((int) $data['page']);
		return $paginator;
	}

        return $this->fetchAll($select);

    }

}